﻿using BasicMoudle.IRepostory;
using BasicMoudle.Repostory;
using Microsoft.Extensions.DependencyInjection;
using Autofac;
using System.Reflection;

namespace BasicMoudle.Model
{
    public class IocModule
    {
        public IocModule() { }

        public void Run()
        {
            //依赖注入
            ServiceCollection services = new ServiceCollection();
            services.AddScoped<IProductRepository, ProductRepository>();
            //services.AddTransient<IProductRepository, ProductTwoRepository>();
            ServiceProvider proVider = services.BuildServiceProvider();
            //var ser = proVider.GetRequiredService<IServiceProvider>();
            //scope

            var one = proVider.GetRequiredService<IProductRepository>();
            Console.WriteLine("1:" + one.GetHashCode());
            Console.WriteLine("2:" + proVider.GetRequiredService<IProductRepository>().GetHashCode());
            var two = proVider.GetService<IProductRepository>();
            var three = proVider.GetServices<IProductRepository>();

            #region
            {
                var scopew = proVider.CreateScope();
                var w = scopew.ServiceProvider;
                Console.WriteLine("3:" + w.GetRequiredService<IProductRepository>().GetHashCode());
                {
                    Console.WriteLine("4:" + w.GetRequiredService<IProductRepository>().GetHashCode());
                }
                {
                    Console.WriteLine("5:" + w.GetRequiredService<IProductRepository>().GetHashCode());
                }
            }
            #endregion

            #region
            {
                var scopew = proVider.CreateScope();
                var w = scopew.ServiceProvider;
                Console.WriteLine("6:" + w.GetRequiredService<IProductRepository>().GetHashCode());
                {
                    Console.WriteLine("7:" + w.GetRequiredService<IProductRepository>().GetHashCode());
                }
                {
                    Console.WriteLine("8:" + w.GetRequiredService<IProductRepository>().GetHashCode());
                }
            }
            #endregion

            ContainerBuilder containerBuilder = new ContainerBuilder();
            //containerBuilder.RegisterType<ProductRepository>().As<IProductRepository>().PropertiesAutowired();
            //containerBuilder.RegisterType<ProductTwoRepository>().As<IProductRepository>().PropertiesAutowired();
            containerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())//加载整个项目
                .Where(t => t.GetInterfaces().Any(x => x == typeof(IProductRepository))) //实现注入过滤
                .AsImplementedInterfaces()//只要实现该接口就注册
                .PropertiesAutowired(); //属性依赖注入
            var container = containerBuilder.Build();
            using (var scope = container.BeginLifetimeScope())
            {
                var service = scope.Resolve<IProductRepository>();
            }
        }
    }
}
